package com.ocom.wxapi.controller;


import com.alibaba.fastjson.JSON;
import com.ocom.common.entity.access.EntityMjGroupPer;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.wx.*;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.AccessListVo;
import com.ocom.common.vo.PersonVo;
import com.ocom.wxapi.client.AccessClientService;
import com.ocom.wxapi.client.HumanClientService;
import com.ocom.wxapi.service.UserInfoPageService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Slf4j
@PreAuthorize("hasRole('ROLE_WX')")
@RequestMapping("/UserInfoPage")
@RestController
public class UserInfoPageController {


    Logger logger= LoggerFactory.getLogger(UserInfoPageController.class);


    @Autowired
    HumanClientService humanClientService;

    @Autowired
    AccessClientService accessClientService;

    @Autowired
    private UserInfoPageService userInfoPageService;

    // 用户信息（UserInfoPage）
    //2.11.1 显示页面（UserInfoPage/onShow）
    @PostMapping("/onShow")
    public Result onShow(@Valid UserInfoPageOnShowRequest request){
        if (StringUtils.isNull(request.getCompanyId())){
            logger.error("单位编号为空");
            return ResultUtil.error(ResultEnum.Err_203,"单位编号为空");
        }
        if (StringUtils.isNull(request.getUserId())){
            logger.error("人员编号为空");
            return ResultUtil.error(ResultEnum.Err_203,"人员编号为空");
        }
        logger.info("用户信息显示页面{{}}",request);
        return userInfoPageService.onShow(request);
    }


    @PostMapping("/updateUser")
    public Result updateUser(@Valid UserInfoPageUpdateUserRequest request){
        PersonVo personVo=new PersonVo();
        personVo.setPId(request.getUserId());
        personVo.setDeptId(0l);
        personVo.setComId(request.getCompanyId());
        personVo.setPCode(request.getPCode());
        personVo.setPIdentity(request.getIdentity());
        personVo.setPName(request.getUserName());
        personVo.setPPhone(request.getTelephone());
        personVo.setPPhotoUrl(request.getPPhotoUrl());
        Result result =humanClientService.UpdatePerson(personVo);
        if(result.getCode()!=200){

            return ResultUtil.error(result.getCode());
        }
        Result accessByUser = accessClientService.getAccessByUser(request.getCompanyId(), request.getPId());
        List<AccessListVo> lists = JSON.parseArray(JSON.toJSONString(accessByUser.getData()), AccessListVo.class);
        logger.info("List<AccessListVo> lists {{}}",lists);
        if (lists !=null && lists.size()>0){
            for (AccessListVo accessListVo: lists) {

                accessClientService.clearAccessByUser(request.getCompanyId(),request.getPId(),request.getUserId());
                UserAccessPageSetAccessRequest userAccessPageSetAccessRequest = new UserAccessPageSetAccessRequest();
                userAccessPageSetAccessRequest.setRegionId(accessListVo.getRegionId());
                userAccessPageSetAccessRequest.setCompanyId(request.getCompanyId());
                userAccessPageSetAccessRequest.setUserId(request.getUserId());
                userAccessPageSetAccessRequest.setAreaNo(accessListVo.getAreaNo());
                userAccessPageSetAccessRequest.setRoleI(2L);
                userAccessPageSetAccessRequest.setPId(request.getPId());
                logger.info("userAccessPageSetAccessRequest{{}}",userAccessPageSetAccessRequest);
                Result result1 = accessClientService.setAccess(userAccessPageSetAccessRequest);
                logger.info("result1{{}}",result1);
                if (result1.getCode() == 200) {

                    EntityMjGroupPer entityMjGroupPer = JSON.parseObject(JSON.toJSONString(result1.getData()), EntityMjGroupPer.class);
                    if (entityMjGroupPer != null) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("userId", entityMjGroupPer.getPId());
                        map.put("role_i", entityMjGroupPer.getGroupNo());
                        logger.info("map{{}}",map);
                        return ResultUtil.info(result1.getCode(), result1.getMsg(), map);
                    }
                }
            }
        }
        EntityPersonnelInfo entityPersonnelInfo=JSON.parseObject(JSON.toJSONString(result.getData()), EntityPersonnelInfo.class);
        return ResultUtil.info(200,"已成功修改"+entityPersonnelInfo.getPName()+"的用户信息");

//        Result result =humanClientService.updateUser(request);
//        if(result.getCode()==200){
//            EntityPersonnelInfo entityPersonnelInfo=JSON.parseObject(JSON.toJSONString(result.getData()), EntityPersonnelInfo.class);
//            return ResultUtil.info(200,"已成功修改"+entityPersonnelInfo.getPName()+"的用户信息");
//        }
//        return ResultUtil.error(ResultEnum.Err_303);
    }


    @PostMapping("/regCode")
    public Result regCode(@Valid UserInfoPageRegCodeRequest request){
        Random random=new Random();
        Integer rend=random.nextInt(89999999);
        rend+=10000000;
        return humanClientService.addEcardRegCode(request.getCompanyId(),request.getUserId(),rend.toString(), DateUtils.getTime());
    }


    @PostMapping("/removeUser")
    public Result removeUser(@Valid UserInfoPageRemoveUserRequest request){

        Result result = humanClientService.removePerson(request.getCompanyId(),0L,request.getUserId());
        logger.info("移除白名单 Result1:"+result.toString());
        //移除白名单
        Result rrr=accessClientService.clearAccessByUser(request.getCompanyId(),request.getPId(),request.getUserId());
        logger.info("移除白名单 Result:"+rrr.toString());

        if(!result.getCode().equals("200")){
            return ResultUtil.error(result.getCode());
        }
        return ResultUtil.success();
//        accessClientService.removeWhiteUser(request.getCompanyId(),request.getUserId());

//        accessClientService.Removeuser(request.getCompanyId(),request.getUserId());

//        Result result =humanClientService.updateUserStatus(request.getCompanyId(),request.getUserId(),1);
//        if(result.getCode()==200){
//            EntityPersonnelInfo entityPersonnelInfo=JSON.parseObject(JSON.toJSONString(result.getData()), EntityPersonnelInfo.class);
//            return ResultUtil.info(200,"已把"+entityPersonnelInfo.getPName()+"移除。");
//        }
//        return ResultUtil.error(ResultEnum.Err_303);
    }

}
